package com.wing.product.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.utils.JsonResult;
import com.wing.device.model.entity.DeviceCategory;
import com.wing.device.model.request.DeviceCategoryForm;
import com.wing.device.model.response.DeviceCategoryVO;
import com.wing.product.dao.ProductMaterialCategoryDao;
import com.wing.product.model.entity.ProductCategory;
import com.wing.product.model.entity.ProductMaterialCategory;
import com.wing.product.model.entity.ProductType;
import com.wing.product.model.request.ProductMaterialCategoryForm;
import com.wing.product.model.response.ProductCategoryVO;
import com.wing.product.model.response.ProductMaterialCategoryVO;
import com.wing.sell.model.response.NodeDataVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 材料分类-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class ProductMaterialCategoryServiceImpl extends ServiceImpl<ProductMaterialCategoryDao, ProductMaterialCategory> implements ProductMaterialCategoryService {

    private static long ROOT_ID=-1l;

    @Override
    public int add(ProductMaterialCategoryForm productMaterialCategoryForm) {

        //校验

        ProductMaterialCategory productMaterialCategory =new ProductMaterialCategory();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(ProductMaterialCategory.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(productMaterialCategoryForm, productMaterialCategory, copyOptions);
        if (productMaterialCategoryForm.getParentId()!=-1){
            ProductMaterialCategory productMaterialCategoryParent=new ProductMaterialCategory();
            productMaterialCategoryParent.setId(productMaterialCategoryForm.getParentId());
            productMaterialCategoryParent.setHasChild(true);
            if (productMaterialCategoryForm.getIsDeleted()){
                productMaterialCategoryParent.setHasEnableChild(true);
            }
            baseMapper.updateById(productMaterialCategoryParent);
        }
        return baseMapper.insert(productMaterialCategory);
    }

    @Override
    public List<ProductMaterialCategoryVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<ProductMaterialCategoryVO> pageList4app(Page page, Map<String, Object> params) {
        List<ProductMaterialCategoryVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public ProductMaterialCategoryVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    @Transactional
    public int del(Long id) {
        ProductMaterialCategoryVO productMaterialCategoryVO=baseMapper.get4appById(id);
        if (productMaterialCategoryVO!=null){
            int delCount=baseMapper.deleteById(id);
            if (productMaterialCategoryVO.getParentId()!=ROOT_ID){
                int count=baseMapper.selectCount(new QueryWrapper<ProductMaterialCategory>().eq("parent_id",productMaterialCategoryVO.getParentId()));
                if (count==0){
                    ProductMaterialCategory productMaterialCategoryParent=new ProductMaterialCategory();
                    productMaterialCategoryParent.setId(productMaterialCategoryVO.getParentId());
                    productMaterialCategoryParent.setHasChild(false);
                    productMaterialCategoryParent.setHasEnableChild(false);
                    baseMapper.updateById(productMaterialCategoryParent);
                }
            }

            return delCount;
        }
        return 0;
    }

    @Override
    @Transactional
    public int enable(Long id) {
        ProductMaterialCategoryVO productMaterialCategoryVO=baseMapper.get4appById(id);
        if (productMaterialCategoryVO!=null){
            ProductMaterialCategory productMaterialCategory=new ProductMaterialCategory();
            productMaterialCategory.setId(id);
            productMaterialCategory.setIsDeleted(true);
            int updateCount=baseMapper.updateById(productMaterialCategory);
            if (productMaterialCategoryVO.getParentId()!=ROOT_ID){
                ProductMaterialCategory productMaterialCategoryParent=new ProductMaterialCategory();
                productMaterialCategoryParent.setId(productMaterialCategoryVO.getParentId());
                productMaterialCategoryParent.setHasEnableChild(true);
                baseMapper.updateById(productMaterialCategoryParent);
            }

            return updateCount;
        }

        return 0;
    }

    @Override
    @Transactional
    public int disable(Long id) {
        ProductMaterialCategoryVO productMaterialCategoryVO=baseMapper.get4appById(id);
        if (productMaterialCategoryVO!=null){
            ProductMaterialCategory productMaterialCategory=new ProductMaterialCategory();
            productMaterialCategory.setId(id);
            productMaterialCategory.setIsDeleted(false);
            int updateCount=baseMapper.updateById(productMaterialCategory);
            if (productMaterialCategoryVO.getParentId()!=ROOT_ID){
                int count=baseMapper.selectCount(new QueryWrapper<ProductMaterialCategory>().eq("parent_id",productMaterialCategoryVO.getParentId()).eq("is_deleted",true));
                if (count==0){
                    ProductMaterialCategory productMaterialCategoryParent=new ProductMaterialCategory();
                    productMaterialCategoryParent.setId(productMaterialCategoryVO.getParentId());
                    productMaterialCategoryParent.setHasEnableChild(false);
                    baseMapper.updateById(productMaterialCategoryParent);
                }
            }

            return updateCount;
        }

        return 0;
    }

    @Override
    @Transactional
    public int update(ProductMaterialCategoryForm productMaterialCategoryForm) {
        ProductMaterialCategoryVO productMaterialCategoryVO=baseMapper.get4appById(productMaterialCategoryForm.getId());
        if (productMaterialCategoryVO!=null){
            if (!productMaterialCategoryVO.getParentId().equals(productMaterialCategoryForm.getParentId())){
                boolean isUpdateEnable=productMaterialCategoryVO.getIsDeleted().equals(productMaterialCategoryForm.getIsDeleted());
                ProductMaterialCategory productMaterialCategory=new ProductMaterialCategory();
                BeanUtils.copyProperties(productMaterialCategoryForm,productMaterialCategory);
                baseMapper.updateById(productMaterialCategory);

                //update new parent category
                if (productMaterialCategoryForm.getParentId()!=ROOT_ID){
                    ProductMaterialCategory parentProducatMaterialCategory=new ProductMaterialCategory();
                    parentProducatMaterialCategory.setId(productMaterialCategoryForm.getParentId());
                    parentProducatMaterialCategory.setHasChild(true);
                    if (productMaterialCategoryForm.getIsDeleted()){
                        parentProducatMaterialCategory.setHasEnableChild(true);
                    }
                    baseMapper.updateById(parentProducatMaterialCategory);
                }


                //update current db product category
                if (productMaterialCategoryVO.getParentId()!=ROOT_ID){
                    int count=baseMapper.selectCount(new QueryWrapper<ProductMaterialCategory>().eq("parent_id",productMaterialCategoryVO.getParentId()));
                    if (count==0){
                        ProductMaterialCategory productMaterialCategoryParent=new ProductMaterialCategory();
                        productMaterialCategoryParent.setId(productMaterialCategoryVO.getParentId());
                        productMaterialCategoryParent.setHasChild(false);
                        baseMapper.updateById(productMaterialCategoryParent);
                    }
//                if (isUpdateEnable&&!deviceCategoryForm.getIsDeleted()){
                    count=baseMapper.selectCount(new QueryWrapper<ProductMaterialCategory>().eq("parent_id",productMaterialCategoryVO.getParentId()).eq("is_deleted",true));
                    if (count==0){
                        ProductMaterialCategory productMaterialCategoryParent=new ProductMaterialCategory();
                        productMaterialCategoryParent.setId(productMaterialCategoryVO.getParentId());
                        productMaterialCategoryParent.setHasEnableChild(false);
                        baseMapper.updateById(productMaterialCategoryParent);
                    }
                    //                }
                }


            }else{
                boolean isUpdateEnable=productMaterialCategoryVO.getIsDeleted().equals(productMaterialCategoryForm.getIsDeleted());
                ProductMaterialCategory productMaterialCategory=new ProductMaterialCategory();
                BeanUtils.copyProperties(productMaterialCategoryForm,productMaterialCategory);
                baseMapper.updateById(productMaterialCategory);
                if (isUpdateEnable&&!productMaterialCategoryForm.getIsDeleted()&&productMaterialCategoryForm.getParentId()!=ROOT_ID){
                    int count=baseMapper.selectCount(new QueryWrapper<ProductMaterialCategory>().eq("parent_id",productMaterialCategoryVO.getParentId()).eq("is_deleted",true));
                    if (count==0){
                        ProductMaterialCategory productMaterialCategoryParent=new ProductMaterialCategory();
                        productMaterialCategoryParent.setId(productMaterialCategoryVO.getParentId());
                        productMaterialCategoryParent.setHasEnableChild(false);
                        baseMapper.updateById(productMaterialCategoryParent);
                    }
                }

            }
        }
        return 0;
    }

    @Override
    public JsonResult getTreeData(Long productMaterialCategoryId) {
        List<Long> productMaterialCategoryIdList = new ArrayList<>();
        if (productMaterialCategoryId != null) {
            productMaterialCategoryIdList = this.baseMapper.getProductTypeHierarchy(productMaterialCategoryId);
        }
        QueryWrapper<ProductMaterialCategory> queryWrapper = new QueryWrapper<>();
        if (productMaterialCategoryId != null) {
            queryWrapper.notIn("id", productMaterialCategoryIdList);
        }

        List<ProductMaterialCategory> list = this.baseMapper.selectList(queryWrapper);
        Map<Long, List<NodeDataVO>> map = new HashMap<>();
        for (ProductMaterialCategory productMaterialCategory : list) {
            if (map.containsKey(productMaterialCategory.getParentId())) {
                NodeDataVO nodeDataVO = new NodeDataVO();
                nodeDataVO.setValue(productMaterialCategory.getId().toString());
                nodeDataVO.setName(productMaterialCategory.getName());
                nodeDataVO.setPid(productMaterialCategory.getParentId().toString());
                map.get(productMaterialCategory.getParentId()).add(nodeDataVO);
            } else {
                List<NodeDataVO> tmpList = new ArrayList<>();
                NodeDataVO nodeDataVO = new NodeDataVO();
                nodeDataVO.setValue(productMaterialCategory.getId().toString());
                nodeDataVO.setName(productMaterialCategory.getName());
                nodeDataVO.setPid(productMaterialCategory.getParentId().toString());
                tmpList.add(nodeDataVO);
                map.put(productMaterialCategory.getParentId(), tmpList);
            }
        }
        List<NodeDataVO> rootList = map.get(-1L);
        if (rootList == null) {
            return JsonResult.success();
        }
        constructTree(rootList, map);
        return JsonResult.success(rootList);
    }

    private void constructTree(List<NodeDataVO> parentList, Map<Long, List<NodeDataVO>> dataMap) {
        for (NodeDataVO node : parentList) {
            Long nodeId = Long.valueOf(node.getValue());
            List<NodeDataVO> childList = dataMap.get(nodeId);
            if (childList != null) {
                node.setChildren(childList);
                constructTree(childList, dataMap);
            }
        }
    }
}
